<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Modal, message } from 'ant-design-vue'
import axios from 'axios'
import { 
  PlusOutlined, 
  ArrowLeftOutlined,
  BoldOutlined,
  ItalicOutlined,
  UnderlineOutlined,
  AlignLeftOutlined,
  AlignCenterOutlined,
  AlignRightOutlined,
  UnorderedListOutlined,
  OrderedListOutlined,
  LinkOutlined,
  PictureOutlined,
  UndoOutlined,
  RedoOutlined
} from '@ant-design/icons-vue'
import type { Dayjs } from 'dayjs'
import {
  createWebsiteContentApi,
  updateWebsiteContentApi,
  getWebsiteContentsApi,
  type CreateWebsiteContentParams,
  type WebsiteContentItem,
} from '~/api/common/login'
import dayjs from 'dayjs'

defineOptions({
  name: 'CreateArticle',
})

const router = useRouter()
const route = useRoute()
const formRef = ref()
const editorContent = ref<HTMLElement>()
const loading = ref(false)
const isEditMode = ref(false)
const articleId = ref<number | null>(null)
const showLinkModal = ref(false)
const linkUrl = ref('')
const linkText = ref('')
const coverPreview = ref('')
// 编辑器状态
const editorState = reactive({
  bold: false,
  italic: false,
  underline: false,
  align: 'left',
  fontSize: '14px',
  fontFamily: '微软雅黑',
  canUndo: false,
  canRedo: false
})
// 表单数据
const formState = reactive<CreateWebsiteContentParams & { publish_time_dayjs?: Dayjs }>({
  channel_id: 1, // 默认首页
  title: '',
  subtitle: '',
  summary: '',
  content: '',
  content_source: '',
  author: '',
  publish_status: 0, // 默认草稿
  publish_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  is_top: 0,
  publish_time_dayjs: dayjs(),
  cover_image: '',
})

// 栏目选项（这里先使用示例数据，后续可以根据实际接口获取）
const channelOptions = ref([
  { label: '首页', value: 1 },
  { label: '考试新闻', value: 2 },
  { label: '通知公告', value: 3 },
  { label: '考试指南', value: 4 },
  { label: '资料下载', value: 5 },
  { label: '关于我们', value: 6 },
])

// 发布状态选项
const publishStatusOptions = [
  { label: '草稿', value: 0 },
  { label: '待审核', value: 1 },
  { label: '已发布', value: 2 },
  { label: '已删除', value: 3 },
]

// 是否置顶选项
const isTopOptions = [
  { label: '否', value: 0 },
  { label: '是', value: 1 },
]

// 表单验证规则
const rules: any = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  subtitle: [
    { required: false, message: '请输入副标题', trigger: 'blur' },
  ],
  summary: [
    { required: false, message: '请输入内容摘要', trigger: 'blur' },
  ],
  content: [
    { required: false, message: '请输入正文', trigger: 'blur' },
  ],
  content_source: [
    { required: false, message: '请输入内容来源', trigger: 'blur' },
  ],
  author: [
    { required: false, message: '请输入作者', trigger: 'blur' },
  ],
  channel_id: [
    { required: false, message: '请选择栏目', trigger: 'change' },
  ],
  publish_time: [
    { required: false, message: '请选择发布日期', trigger: 'change' },
  ],
}
// 计算属性
const wordCount = computed(() => {
  const text = formState.content.replace(/<[^>]*>/g, '')
  return text.length
})
const updateUndoRedoState = () => {
  // 这里可以添加更复杂的撤销重做状态管理
  // 目前使用简单的实现
  editorState.canUndo = true
  editorState.canRedo = true
}

// 富文本编辑器方法
const handleEditorInput = () => {
  if (editorContent.value) {
    formState.content = editorContent.value.innerHTML
    // 更新撤销重做状态
    updateUndoRedoState()
  }
}

const handleEditorBlur = () => {
  if (editorContent.value) {
    formState.content = editorContent.value.innerHTML
  }
}

const handleEditorFocus = () => {
  // 编辑器获得焦点时的处理
}
// 处理日期变化
function handleDateChange(value: string | Dayjs, dateString: string) {
  if (value && typeof value !== 'string') {
    formState.publish_time_dayjs = value
    formState.publish_time = value.format('YYYY-MM-DD HH:mm:ss')
  } else if (dateString) {
    formState.publish_time = dateString
  }
}

// 加载文章详情（编辑模式）- 通过列表接口获取，然后查找对应的项
async function loadArticleDetail() {
  if (!articleId.value) return

  loading.value = true
  try {
    // 通过列表接口获取所有内容（不传 channel_id 获取所有栏目的数据）
    const response = await getWebsiteContentsApi({})
    if (response.code === 0 && response.data && Array.isArray(response.data)) {
      // 从列表中查找对应的项
      let article = response.data.find((item: WebsiteContentItem) => item.id === articleId.value)
      
      // 如果找不到，尝试通过已知的 channel_id 获取（从列表中获取所有不同的 channel_id）
      if (!article) {
        const channelIds = [...new Set(response.data.map((item: WebsiteContentItem) => item.channel_id))]
        for (const channelId of channelIds) {
          try {
            const channelResponse = await getWebsiteContentsApi({ channel_id: channelId })
            if (channelResponse.code === 0 && channelResponse.data && Array.isArray(channelResponse.data)) {
              article = channelResponse.data.find((item: WebsiteContentItem) => item.id === articleId.value)
              if (article) {
                break
              }
            }
          } catch (e) {
            // 继续尝试下一个 channel_id
          }
        }
      }
      
      if (article) {
        formState.channel_id = article.channel_id
        formState.title = article.title
        formState.subtitle = article.subtitle
        formState.summary = article.summary
        formState.content = article.content
        formState.content_source = article.content_source
        formState.author = article.author
        formState.publish_status = article.publish_status
        formState.publish_time = article.publish_time
        formState.is_top = article.is_top
        formState.publish_time_dayjs = dayjs(article.publish_time)
        formState.cover_image = article.cover_image || (article as any).cover_url || ''
      } else {
        message.error('未找到该文章')
        router.push({ name: 'DashboardAnalysis' })
      }
    } else {
      message.error('加载文章详情失败')
      router.push({ name: 'DashboardAnalysis' })
    }
  } catch (error: any) {
    console.error('加载文章详情失败:', error)
    message.error('加载文章详情失败，请稍后重试')
    router.push({ name: 'DashboardAnalysis' })
  } finally {
    loading.value = false
  }
}
const toggleBold = () => {
  document.execCommand('bold')
  editorState.bold = !editorState.bold
}
// 提交表单（保存）
async function handleSubmit() {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    // 准备提交数据
    const submitData: CreateWebsiteContentParams = {
      channel_id: formState.channel_id,
      title: formState.title,
      subtitle: formState.subtitle,
      summary: formState.summary,
      content: formState.content,
      content_source: formState.content_source,
      author: formState.author,
      publish_status: formState.publish_status,
      publish_time: formState.publish_time,
      is_top: formState.is_top,
      cover_image: formState.cover_image,
    }
    
    let response
    if (isEditMode.value && articleId.value) {
      // 编辑模式：更新文章
      response = await updateWebsiteContentApi({
        id: articleId.value,
        ...submitData,
      })
    } else {
      // 新建模式：创建文章
      response = await createWebsiteContentApi(submitData)
    }
    
    if (response.code === 0) {
      Modal.success({
        title: '提示',
        content: isEditMode.value ? '更新成功' : '创建成功',
        okText: '确定',
        okButtonProps: { style: { backgroundColor: '#428bca', border: 'none', borderRadius: '0' } } as any,
        centered: true,
        onOk: () => {
          // 返回列表页面
          router.push({ name: 'DashboardAnalysis' })
        },
      })
    } else {
      const errorMsg = (response as any).message || (response as any).msg || (isEditMode.value ? '更新失败' : '创建失败')
      message.error(errorMsg)
    }
  } catch (error: any) {
    if (error.isBusinessError) {
      message.error(error.message || (isEditMode.value ? '更新失败' : '创建失败'))
    } else {
      console.error(isEditMode.value ? '更新文章失败:' : '创建文章失败:', error)
      message.error(isEditMode.value ? '更新失败，请稍后重试' : '创建失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 发布文章（直接发布）
async function handlePublish() {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    // 准备提交数据，发布状态设为已发布（2）
    const submitData: CreateWebsiteContentParams = {
      channel_id: formState.channel_id,
      title: formState.title,
      subtitle: formState.subtitle,
      summary: formState.summary,
      content: formState.content,
      content_source: formState.content_source,
      author: formState.author,
      publish_status: 1, // 待审核
      publish_time: formState.publish_time,
      is_top: formState.is_top,
      cover_image: formState.cover_image,
    }
    
    let response
    if (isEditMode.value && articleId.value) {
      // 编辑模式：更新文章并发布
      response = await updateWebsiteContentApi({
        id: articleId.value,
        ...submitData,
      })
    } else {
      // 新建模式：创建文章并发布
      response = await createWebsiteContentApi(submitData)
    }
    
    if (response.code === 0) {
      Modal.success({
        title: '提示',
        content: '已提交审核',
        okText: '确定',
        okButtonProps: { style: { backgroundColor: '#428bca', border: 'none', borderRadius: '0' } } as any,
        centered: true,
        onOk: () => {
          // 返回列表页面
          router.push({ name: 'DashboardAnalysis' })
        },
      })
    } else {
      const errorMsg = (response as any).message || (response as any).msg || '发布失败'
      message.error(errorMsg)
    }
  } catch (error: any) {
    if (error.isBusinessError) {
      message.error(error.message || '发布失败')
    } else {
      console.error('发布文章失败:', error)
      message.error('发布失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 取消并返回
function handleCancel() {
  router.push({ name: 'DashboardAnalysis' })
}

// 初始化：判断是新建还是编辑模式
onMounted(() => {
  const id = route.params.id
  if (id) {
    isEditMode.value = true
    articleId.value = Number(id)
    loadArticleDetail()
  }
})

watch(() => formState.cover_image, (val) => {
  coverPreview.value = val || ''
}, { immediate: true })

async function uploadFileToCloud(file: File): Promise<string | null> {
  try {
    const formData = new FormData()
    formData.append('subsystem_code', 'electricity-service')
    formData.append('subsystem_api', 'clue-macro-trace')
    formData.append('files', file)

    const response = await axios.post(
      'https://api-file-manage.airqualitychina.cn:9998/api/hold-filename-upload',
      formData,
      { timeout: 30000 },
    )

    const responseData = response.data
    if (responseData?.code === 2000) {
      const resultData = responseData.result
      if (Array.isArray(resultData) && resultData.length > 0) {
        const filePath = resultData[0]?.url
        if (filePath) {
          const fullUrl = `https://f.hotgrid.cn/${filePath}`
          return fullUrl
        }
      }
    }

    message.error(responseData?.message || '上传失败，请重试')
    return null
  } catch (error: any) {
    console.error('文件上传错误:', error)
    message.error(error?.response?.data?.message || error?.message || '上传失败，请重试')
    return null
  }
}
const toggleItalic = () => {
  document.execCommand('italic')
  editorState.italic = !editorState.italic
}

const toggleUnderline = () => {
  document.execCommand('underline')
  editorState.underline = !editorState.underline
}
async function handleCoverUpload(file: File) {
  const hide = message.loading('封面上传中...', 0)
  try {
    const url = await uploadFileToCloud(file)
    if (url) {
      formState.cover_image = url
      coverPreview.value = url
      message.success('封面上传成功')
    }
  } finally {
    hide?.()
  }
  return false
}
const setAlign = (align: string) => {
  document.execCommand('justify' + align.charAt(0).toUpperCase() + align.slice(1))
  editorState.align = align
}

const insertList = (type: string) => {
  document.execCommand(type === 'ul' ? 'insertUnorderedList' : 'insertOrderedList')
}
const handleImageUpload = async () => {
  // 触发文件选择
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = async (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      const hide = message.loading('图片上传中...', 0)
      try {
        const url = await uploadFileToCloud(file)
        if (url && editorContent.value) {
          // 插入图片到编辑器
          const imgHtml = `<img src="${url}" alt="上传的图片" style="max-width: 100%; height: auto;" />`
          document.execCommand('insertHTML', false, imgHtml)
          handleEditorInput()
          message.success('图片上传成功')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        message.error('图片上传失败，请重试')
      } finally {
        hide?.()
      }
    }
  }
  input.click()
}
const undo = () => {
  document.execCommand('undo')
}

const redo = () => {
  document.execCommand('redo')
}
const insertLink = () => {
  if (linkUrl.value) {
    const linkHtml = `<a href="${linkUrl.value}" target="_blank">${linkText.value || linkUrl.value}</a>`
    document.execCommand('insertHTML', false, linkHtml)
    showLinkModal.value = false
    linkUrl.value = ''
    linkText.value = ''
    handleEditorInput()
  }
}
</script>

<template>
  <page-container>
    <div class="create-article-container">
      <div class="page-header">
        <a-button class="back-btn" @click="handleCancel">
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button>
        <h2 class="page-title">{{ isEditMode ? '编辑文章' : '新建文章' }}</h2>
        <div class="header-actions">
          <a-button
            type="primary"
            :loading="loading"
            class="publish-btn"
            @click="handlePublish"
          >
            发布
          </a-button>
          <a-button
            :loading="loading"
            class="save-btn"
            @click="handleSubmit"
          >
            {{ isEditMode ? '保存' : '保存草稿' }}
          </a-button>
          <a-button
            class="cancel-btn"
            @click="handleCancel"
          >
            取消
          </a-button>
        </div>
      </div>
      
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        class="article-form"
      >
        <div class="form-layout">
          <!-- 左侧：正文内容（70%） -->
          <div class="form-left">
            <div class="content-section">
              <div class="section-header">
                <h3 class="section-title">正文内容</h3>
              </div>
              <a-form-item name="content" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
                <!-- 富文本编辑器 -->
                <div class="rich-text-editor">
                  <div class="editor-toolbar">
                    <a-space size="small" wrap>
                      <!-- 字体样式 -->
                      <a-select 
                        v-model:value="editorState.fontSize" 
                        size="small" 
                        style="width: 80px"
                        placeholder="字体大小"
                      >
                        <a-select-option value="12px">12px</a-select-option>
                        <a-select-option value="14px">14px</a-select-option>
                        <a-select-option value="16px">16px</a-select-option>
                        <a-select-option value="18px">18px</a-select-option>
                        <a-select-option value="20px">20px</a-select-option>
                        <a-select-option value="24px">24px</a-select-option>
                      </a-select>
                      
                      <a-select 
                        v-model:value="editorState.fontFamily" 
                        size="small" 
                        style="width: 100px"
                        placeholder="字体"
                      >
                        <a-select-option value="Arial">Arial</a-select-option>
                        <a-select-option value="微软雅黑">微软雅黑</a-select-option>
                        <a-select-option value="宋体">宋体</a-select-option>
                        <a-select-option value="黑体">黑体</a-select-option>
                        <a-select-option value="楷体">楷体</a-select-option>
                      </a-select>
                      
                      <!-- 文本格式 -->
                      <a-button 
                        size="small" 
                        :type="editorState.bold ? 'primary' : 'default'"
                        @click="toggleBold"
                      >
                        <template #icon><BoldOutlined /></template>
                      </a-button>
                      <a-button 
                        size="small" 
                        :type="editorState.italic ? 'primary' : 'default'"
                        @click="toggleItalic"
                      >
                        <template #icon><ItalicOutlined /></template>
                      </a-button>
                      <a-button 
                        size="small" 
                        :type="editorState.underline ? 'primary' : 'default'"
                        @click="toggleUnderline"
                      >
                        <template #icon><UnderlineOutlined /></template>
                      </a-button>
                      
                      <!-- 对齐方式 -->
                      <a-button-group size="small">
                        <a-button 
                          :type="editorState.align === 'left' ? 'primary' : 'default'"
                          @click="setAlign('left')"
                        >
                          <template #icon><AlignLeftOutlined /></template>
                        </a-button>
                        <a-button 
                          :type="editorState.align === 'center' ? 'primary' : 'default'"
                          @click="setAlign('center')"
                        >
                          <template #icon><AlignCenterOutlined /></template>
                        </a-button>
                        <a-button 
                          :type="editorState.align === 'right' ? 'primary' : 'default'"
                          @click="setAlign('right')"
                        >
                          <template #icon><AlignRightOutlined /></template>
                        </a-button>
                      </a-button-group>
                      
                      <!-- 列表 -->
                      <a-button 
                        size="small" 
                        @click="insertList('ul')"
                      >
                        <template #icon><UnorderedListOutlined /></template>
                      </a-button>
                      <a-button 
                        size="small" 
                        @click="insertList('ol')"
                      >
                        <template #icon><OrderedListOutlined /></template>
                      </a-button>
                      
                      <!-- 插入链接和图片 -->
                      <a-button 
                        size="small" 
                        @click="showLinkModal = true"
                      >
                        <template #icon><LinkOutlined /></template>
                      </a-button>
                      <a-button 
                        size="small" 
                        @click="handleImageUpload"
                      >
                        <template #icon><PictureOutlined /></template>
                      </a-button>
                      
                      <!-- 撤销重做 -->
                      <a-button 
                        size="small" 
                        @click="undo"
                        :disabled="!editorState.canUndo"
                      >
                        <template #icon><UndoOutlined /></template>
                      </a-button>
                      <a-button 
                        size="small" 
                        @click="redo"
                        :disabled="!editorState.canRedo"
                      >
                        <template #icon><RedoOutlined /></template>
                      </a-button>
                    </a-space>
                  </div>
                  
                  <div 
                    ref="editorContent"
                    class="editor-content"
                    contenteditable="true"
                    @input="handleEditorInput"
                    @blur="handleEditorBlur"
                    @focus="handleEditorFocus"
                    v-html="formState.content"
                  ></div>
 
                  
                  <div class="editor-footer">
                    <span class="word-count">字数：{{ wordCount }}</span>
                  </div>
                </div>
              </a-form-item>
            </div>
          </div>
          
          <!-- 右侧：其他信息（30%） -->
          <div class="form-right">
            <div class="info-section">
              <div class="section-header">
                <h3 class="section-title">文章信息</h3>
              </div>
              
              <a-form-item label="标题" name="title" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-input
                  v-model:value="formState.title"
                  placeholder="请输入标题"
                  :maxlength="200"
                  show-count
                />
              </a-form-item>
              
              <a-form-item 
                style="display: none;"
                label="副标题" name="subtitle" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-input
                  v-model:value="formState.subtitle"
                  placeholder="请输入副标题"
                  :maxlength="200"
                  show-count
                />
              </a-form-item>
              
              <a-form-item label="内容摘要" name="summary" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-textarea
                  v-model:value="formState.summary"
                  placeholder="请输入内容摘要"
                  :rows="4"
                  :maxlength="500"
                  show-count
                />
              </a-form-item>
              
              <a-form-item label="作者" name="author" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-input
                  v-model:value="formState.author"
                  placeholder="请输入作者"
                  :maxlength="50"
                />
              </a-form-item>
              
              <a-form-item label="内容来源"
               name="content_source" 
               :required="false"
               :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-input
                  v-model:value="formState.content_source"
                  placeholder="请输入内容来源"
                  :maxlength="100"
                />
              </a-form-item>

              <a-form-item label="封面图" name="cover_image" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <div class="cover-field">
                  <a-upload
                    :before-upload="handleCoverUpload"
                    :show-upload-list="false"
                  >
                    <a-button type="dashed" block>
                      <template #icon>
                        <PlusOutlined />
                      </template>
                      上传封面
                    </a-button>
                  </a-upload>
                  <a-input
                    v-model:value="formState.cover_image"
                    placeholder="或粘贴图片地址"
                    allow-clear
                    class="cover-url-input"
                  />
                </div>
                <div
                  v-if="coverPreview"
                  class="cover-preview"
                >
                  <img :src="coverPreview" alt="封面预览">
                </div>
                <div v-else class="cover-preview placeholder">
                  <span>封面预览区域</span>
                </div>
              </a-form-item>
              
              <a-form-item label="栏目" name="channel_id" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-select
                  v-model:value="formState.channel_id"
                  placeholder="请选择栏目"
                  style="width: 100%"
                >
                  <a-select-option
                    v-for="option in channelOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item label="发布日期" name="publish_time" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-date-picker
                  v-model:value="formState.publish_time_dayjs"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择发布日期"
                  style="width: 100%"
                  @change="handleDateChange"
                />
              </a-form-item>
              
              <a-form-item label="发布状态" name="publish_status" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-radio-group v-model:value="formState.publish_status">
                  <a-radio
                    v-for="option in publishStatusOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-radio>
                </a-radio-group>
              </a-form-item>
              
              <a-form-item label="是否置顶" name="is_top" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-radio-group v-model:value="formState.is_top">
                  <a-radio
                    v-for="option in isTopOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </a-radio>
                </a-radio-group>
              </a-form-item>
            </div>
          </div>
        </div>
      </a-form>

      <!-- 插入链接弹窗 -->
      <a-modal
        v-model:open="showLinkModal"
        title="插入链接"
        @ok="insertLink"
        @cancel="showLinkModal = false"
      >
        <a-form layout="vertical">
          <a-form-item label="链接地址">
            <a-input v-model:value="linkUrl" placeholder="请输入链接地址" />
          </a-form-item>
          <a-form-item label="链接文本">
            <a-input v-model:value="linkText" placeholder="请输入链接文本" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </page-container>
</template>

<style scoped lang="less">

@import './index.css';
.create-article-container {
  position: relative;
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 16px 20px;
}

.back-btn {
  margin-right: 16px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

/* 头部操作按钮 */
.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.publish-btn {
  background: #1890ff;
  border-color: #1890ff;
}

.save-btn {
  color: #1890ff;
  border-color: #1890ff;
}

.cancel-btn {
  color: #666;
  border-color: #d9d9d9;
}

.article-form {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-layout {
  display: flex;
  gap: 24px;
}

.form-left {
  flex: 7;
}

.form-right {
  flex: 3;
}

.content-section,
.info-section {
  background: white;
  border-radius: 8px;
}

.section-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 富文本编辑器样式 */
.rich-text-editor {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.editor-toolbar {
  background: #fafafa;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.editor-toolbar .ant-space {
  width: 100%;
}

.editor-content {
  min-height: 400px;
  max-height: 600px;
  padding: 16px;
  line-height: 1.6;
  overflow-y: auto;
  overflow-x: hidden;
  outline: none;
  font-size: 14px;
  word-wrap: break-word;
  
  img {
    max-width: 100% !important;
    height: auto !important;
    display: block;
    margin: 8px 0;
  }
}

.editor-content:focus {
  border-color: #40a9ff;
}

.editor-footer {
  background: #fafafa;
  padding: 8px 16px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
  color: #666;
  font-size: 12px;
}

/* 封面图样式 */
.cover-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.cover-url-input {
  margin-top: 8px;
}

.cover-preview {
  margin-top: 12px;
  width: 100%;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.cover-preview.placeholder {
  background: #fafafa;
  color: #999;
}

.cover-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .form-layout {
    flex-direction: column;
  }
  
  .fixed-action-buttons {
    position: static;
    flex-direction: row;
    justify-content: flex-end;
    margin-bottom: 20px;
    box-shadow: none;
    padding: 0;
    background: transparent;
  }
  
  .fixed-action-buttons .ant-btn {
    width: auto;
    min-width: 80px;
  }
}

@media (max-width: 768px) {
  .create-article-container {
    padding: 12px;
  }
  
  .page-header {
    padding: 12px 16px;
  }
  
  .fixed-action-buttons {
    flex-wrap: wrap;
  }
  
  .editor-toolbar .ant-space {
    flex-wrap: wrap;
  }
}
.create-article-container {
  padding: 0;
  background-color: transparent;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px 0;
  background-color: transparent;
}

.back-btn {
  border-radius: 0;
  border-color: #428bca;
  color: #428bca;
  
  &:hover {
    color: #fff;
    background: #428bca;
    border-color: #428bca;
  }
}

.page-title {
  flex: 1;
  font-size: 24px;
  font-weight: 600;
  color: #428bca;
  margin: 0;
}

.article-form {
  :deep(.ant-form-item-label) {
    font-weight: 500;
    color: #333;
  }
  
  :deep(.ant-input),
  :deep(.ant-input-affix-wrapper),
  :deep(.ant-select-selector),
  :deep(.ant-picker) {
    border-radius: 4px;
  }
  
  :deep(.ant-upload-select-picture-card) {
    border-radius: 4px;
  }
}

.form-layout {
  display: flex;
  gap: 24px;
  align-items: flex-start;
  width: 100%;
  max-width: 100%;
  overflow: hidden;
}

.form-left {
  flex: 0 0 calc(70% - 12px);
  min-width: 0;
  padding: 0;
}

.form-right {
  flex: 0 0 calc(30% - 12px);
  min-width: 300px;
  max-width: calc(30% - 12px);
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 0;
}

.content-section {
  width: 100%;
}

.section-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 3px solid #428bca;
}

.section-title {
  font-size: 20px;
  font-weight: 700;
  color: #428bca;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  
  &::before {
    content: '';
    width: 4px;
    height: 20px;
    background: linear-gradient(135deg, #428bca, #5c9cd6);
    border-radius: 2px;
  }
}

.content-textarea {
  font-size: 16px;
  line-height: 1.8;
  
  :deep(.ant-input) {
    font-size: 16px;
    line-height: 1.8;
    padding: 20px;
    border: 1px solid #d9d9d9;
    transition: all 0.3s;
    
    &:focus {
      border-color: #428bca;
      box-shadow: 0 0 0 2px rgba(66, 139, 202, 0.1);
    }
  }
}

.info-section {
  padding: 0;
  width: 100%;
  min-width: 0;
  
  :deep(.ant-form-item-label) {
    font-weight: 600;
  }
  
  :deep(.ant-input),
  :deep(.ant-input-affix-wrapper),
  :deep(.ant-select-selector),
  :deep(.ant-picker) {
    border-radius: 4px;
    transition: all 0.3s;
    
    &:hover {
      border-color: #428bca;
    }
    
    &:focus,
    &.ant-picker-focused {
      border-color: #428bca;
      box-shadow: 0 0 0 2px rgba(66, 139, 202, 0.1);
    }
  }
  
  :deep(.ant-radio-group) {
    .ant-radio-wrapper {
      margin-right: 16px;
      
      .ant-radio-inner {
        border-color: #428bca;
      }
      
      .ant-radio-checked .ant-radio-inner {
        background-color: #428bca;
        border-color: #428bca;
      }
    }
  }
}

.cover-field {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.cover-preview {
  margin-top: 12px;
  width: 100%;
  min-height: 140px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;

  &.placeholder {
    color: #999;
    font-size: 14px;
  }

  img {
    max-width: 100%;
    max-height: 220px;
    object-fit: cover;
    border-radius: 4px;
  }
}

.cover-url-input {
  width: 100%;
}

.upload-tip {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.publish-btn {
  background: linear-gradient(135deg, #428bca, #5c9cd6);
  border: none;
  border-radius: 4px;
  width: 100%;
  height: 44px;
  font-weight: 500;
  font-size: 16px;
  
  &:hover {
    opacity: 0.92;
  }
}

.save-btn {
  border-radius: 4px;
  border-color: #428bca;
  color: #428bca;
  width: 100%;
  height: 44px;
  font-weight: 500;
  font-size: 16px;
  
  &:hover {
    color: #fff;
    background: #428bca;
    border-color: #428bca;
  }
}

.cancel-btn {
  border-radius: 4px;
  border-color: #d9d9d9;
  color: #666;
  width: 100%;
  height: 44px;
  font-weight: 500;
  font-size: 16px;
  
  &:hover {
    color: #428bca;
    border-color: #428bca;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .form-layout {
    flex-direction: column;
  }
  
  .form-left,
  .form-right {
    flex: 1 1 100%;
  }
  
  .action-buttons {
    position: static;
  }
}
</style>
